//
//  CloudStorageSDK.swift
//  Game106Client-mobile
//
//  Created by Developer001 on 2025/5/14.
//

import Foundation
import AppTrackingTransparency
import AdSupport

@objc class CloudStorageSDK : NSObject, SDKDelegate {
    
    // 静态变量持有单例实例
    @MainActor
    static var instance: CloudStorageSDK?
    
    var viewController :UIViewController?
    
    let cloudStore = NSUbiquitousKeyValueStore.default
    
    @MainActor
    @objc func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        print("@CloudStorageSDK launched")
        
        CloudStorageSDK.instance = self
        
        if let window = application.delegate?.window {
            viewController = window?.rootViewController
        }
        JsbSDK.onMsg("CloudStorageSDK.requestSaveGameData", handler: self.saveGameData);
        JsbSDK.onMsg("CloudStorageSDK.requestLoadGameData", handler: self.loadGameData);
        JsbSDK.onMsg("CloudStorageSDK.requestDeleteGameData", handler: self.deleteGameData);
        
        return true
    }
    
    func saveGameData(args:String?) {
        if let jsonData = args?.data(using: .utf8) {
            do {
                if let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                    let data = json["data"] as? String
                    print("@saveGameData data is \(data!)")
                    cloudStore.set(data, forKey: "playerSave")
                }
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }
    }
    
    func loadGameData(args:String?) {
        let data = cloudStore.string(forKey: "playerSave")
        JsbSDK.sendMsg("CloudStorageSDKManager.responseLoadGameData", args: ["data": data as Any])
    }

    func deleteGameData(args:String?) {
        cloudStore.removeObject(forKey: "playerSave")
        cloudStore.synchronize()
        print("PlayerSave in cloud is deleted!")
    }
    
}
